package com.shemy.sshiro.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.io.UnsupportedEncodingException;
import java.util.Date;

/**
 * @Description JwtUtil
 * @Author Dzsom
 * @Date 2019-05-14 10:25
 * @Encoding UTF-8
 * @Version 1.0
 **/
public class JwtUtil {

    private static final long EXPIRE_TIME = 5* 60 * 60 * 1000;

    /**
     * 校验Token
     * @param token
     * @param username
     * @param password
     * @return
     */
    public static boolean verify(String token,String username,String password){
        try {
            Algorithm algorithm=Algorithm.HMAC256(password);
            JWTVerifier verifier = JWT.require(algorithm).withClaim("username", username).build();
            verifier.verify(token);
            return true;
        } catch (Exception e) {
           return false;
        }
    }

    /**
     * 获取用户名
     * @param token
     * @return
     */
    public static String getUsername(String token){
        try {
            DecodedJWT jwt = JWT.decode(token);
            return jwt.getClaim("username").asString();
        } catch (JWTDecodeException e) {
            return null;
        }
    }

    /**
     * 生成签名
     * @param username
     * @param password
     * @return
     */
    public static String sign(String username,String password){

        try {
            Date date = new Date(System.currentTimeMillis() + EXPIRE_TIME);
            Algorithm algorithm=Algorithm.HMAC256(password);
            return JWT.create()
                    .withClaim("username",username)
                    .withExpiresAt(date)
                    .sign(algorithm);
        } catch (UnsupportedEncodingException e) {
            return null;
        }

    }



}
